package org.redis.cluster.transport.netty.protocol;

import java.util.List;

import org.redis.cluster.transport.ByteBuffer;
import org.redis.cluster.transport.netty.NettyByteBuffer;
import org.redis.cluster.transport.netty.server.NettyServerSession;
import org.redis.cluster.transport.protocol.ProtocolDecoder;
import org.redis.cluster.transport.protocol.ProtocolOutput;
import org.redis.cluster.transport.session.Session;
import org.redis.cluster.transport.session.SessionContext;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

public class NettyDecoder extends ByteToMessageDecoder {
	
	private ProtocolDecoder decoder;
	private SessionContext context;
	
	public NettyDecoder(ProtocolDecoder decoder,SessionContext context) {
		this.decoder=decoder;
		this.context=context;
	}

	@Override
	protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
		ByteBuffer buffer=getByteBuffer(in);
		Session session=getSession(ctx);
		ProtocolOutput output=getOutput(out);
		decoder.decode(buffer, session, output);
	}
	
	protected ByteBuffer getByteBuffer(ByteBuf in) {
		return new NettyByteBuffer(in);
	}
	
	protected Session getSession(ChannelHandlerContext ctx) {
		return new NettyServerSession(ctx,context);
	}
	
	protected ProtocolOutput getOutput(List<Object> out) {
		return new NettyProtocolOutput(out);
	}
}